import { useState, useCallback, useEffect } from 'react'
import { ChatMessage, ChatState } from '@/types'
import useTxtAudio from './useTxtAudio'

/**
 * 聊天配置选项
 */
interface ChatConfig {
  /** API 端点，默认为 '/api/chat' */
  apiEndpoint?: string
  /** 请求超时时间（毫秒），默认30秒 */
  timeout?: number
  /** 最大重试次数，默认2次 */
  maxRetries?: number
}

/**
 * 聊天Hook，提供聊天功能
 * @param config 配置选项
 * @returns 聊天状态和操作方法
 */
export const useChat = (config: ChatConfig = {}) => {
  const {
    apiEndpoint = '/api/chat'
  } = config

  const { initAudio, endAudio, saveAudio } = useTxtAudio();

  const [chatState, setChatState] = useState<ChatState>({
    messages: [],
    isLoading: false,
    error: null,
  })
  const sendMessage = useCallback(async (content: string) => {
    if (!content.trim()) return

    const userMessage: ChatMessage = {
      id: Date.now().toString(),
      role: 'user',
      content: content.trim(),
      timestamp: new Date(),
    }

    // 添加用户消息
    setChatState(prev => ({
      ...prev,
      messages: [...prev.messages, userMessage],
      isLoading: true,
      error: null,
    }))

    try {

      const response = await fetch(apiEndpoint, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          messages: [...chatState.messages, userMessage].map(msg => ({
            role: msg.role,
            content: msg.content,
          }))
        }),
      })

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      }

      const reader = response.body?.getReader()
      if (!reader) {
        throw new Error('No response stream')
      }

      const assistantMessage: ChatMessage = {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: '',
        timestamp: new Date(),
      }

      setChatState(prev => ({
        ...prev,
        messages: [...prev.messages, assistantMessage],
        isLoading: false,
      }))

      const decoder = new TextDecoder()
      let messages = ""
      initAudio()

      while (true) {
        const { done, value } = await reader.read()
        if (done) break

        const chunk = decoder.decode(value)
        const lines = chunk.split('\n')

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const data = line.slice(6)
            if (data === '[DONE]') {
              endAudio(messages)
              break
            }

            try {
              const parsed = JSON.parse(data)
              messages = messages + parsed.content
              saveAudio(messages)

              if (parsed.content) {
                setChatState(prev => ({
                  ...prev,
                  messages: prev.messages.map(msg =>
                    msg.id === assistantMessage.id
                      ? { ...msg, content: msg.content + parsed.content }
                      : msg
                  ),
                }))
              }
            } catch (e) {
              console.error('Failed to parse stream data:', e)
            }
          }
        }
      }
    } catch (error) {
      console.error('Chat error:', error)

      let errorMessage = 'Something went wrong'

      if (error instanceof Error) {
        if (error.message.includes('HTTP 401')) {
          errorMessage = 'API密钥无效，请检查配置'
        } else if (error.message.includes('HTTP 429')) {
          errorMessage = '请求过于频繁，请稍后再试'
        } else if (error.message.includes('HTTP 500')) {
          errorMessage = '服务器错误，请稍后再试'
        } else if (error.message.includes('Failed to fetch')) {
          errorMessage = '网络连接失败，请检查网络'
        } else {
          errorMessage = error.message
        }
      }

      setChatState(prev => ({
        ...prev,
        isLoading: false,
        error: errorMessage,
      }))
    }
  }, [chatState.messages, apiEndpoint])

  const clearMessages = useCallback(() => {
    setChatState({
      messages: [],
      isLoading: false,
      error: null,
    })
  }, [])

  return {
    messages: chatState.messages,
    isLoading: chatState.isLoading,
    error: chatState.error,
    sendMessage,
    clearMessages,
  }
}